<template>
  <el-form
    ref="merDataField"
    size="small"
    :rules="ruleValidate"
    :model="merData"
    label-width="130px"
    @submit.native.prevent
    >
    <el-tabs v-loading="loading" type="border-card" v-model="activeName">
      <el-tab-pane label="基本信息" name="detail">
        <div class="section">
          <div class="title">基础信息</div>
          <el-row :gutter="24" class="mt20">
            <el-col :span="12">
              <el-form-item label="名称：" prop="mer_name">
                <el-input
                  v-model="merData.mer_name"
                  placeholder="请填写名称"
                  class="selWidth"
                />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="手机号：" prop="phone">
                <el-input
                  v-model="merData.phone"
                  placeholder="请填写手机号"
                  class="selWidth"
                />
              </el-form-item>
            </el-col>

          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="分类：" prop="category_id" >
               <el-select
                  v-model="merData.category_id"
                  placeholder="请选择"
                  class="selWidth"
                  filterable
                >
                  <el-option
                    v-for="item in merCateList"
                    :key="item.merchant_category_id"
                    :label="item.category_name"
                    :value="item.merchant_category_id"
                  />
                </el-select>
              </el-form-item>
            </el-col>


            <el-col :span="12">
              <el-form-item prop="province" style="margin-right:10px" label="省">
                <el-select v-model="merData.province" placeholder="请选择省" size="small" filterable
                           @change="addressSelect(merData.province,2)">
                  <el-option v-for="item in provinceOptions" :key="item.id" :label="item.name" :value="item.name">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="city" style="margin-right:10px" label="市">
                <el-select v-model="merData.city" placeholder="请选择市" size="small" filterable
                           @change="addressSelect(merData.city,3)">
                  <el-option v-for="item in cityOptions" :key="item.id" :label="item.name" :value="item.name">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="district" style="margin-right:10px" label="区">
                <el-select v-model="merData.district" placeholder="请选择区" size="small" filterable
                           @change="addressSelect(merData.district,4)">
                  <el-option v-for="item in districtOptions" :key="item.id" :label="item.name" :value="item.name">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item prop="street" style="margin-right:10px" label="镇">
                <el-select v-model="merData.street" placeholder="请选择镇" size="small" filterable
                           @change="addressSelect(merData.street,5)">
                  <el-option v-for="item in townOptions" :key="item.id" :label="item.name" :value="item.name">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

          </el-row>
        </div>
      </el-tab-pane>
  </el-tabs>
</el-form>
</template>
<script>
import { merCategoryListApi } from '@/api/product'
import LazyCascader from '@/components/lazyCascader'
import { getstoreTypeApi, merchantUpdate, merchantCreate,getywyuidlist ,merchantInteCreate} from "@/api/merchant";
import {cityDataLst} from "@/api/system";
export default {
  components: {
    LazyCascader
  },
  props: {
    merData: {
      type: Object,
      default: {},
    },
    isAdd: {
      type: Boolean,
      default: false,
    }
  },
  data() {
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请填写联系方式'))
      } else if (!/^1[3456789]\d{9}$/.test(value)) {
        callback(new Error('格式不正确!'))
      } else {
        callback()
      }
    }
    return {
      provinceOptions: [],
      cityOptions: [],
      districtOptions: [],
      townOptions:[],
      loading: false,
      city_ids:'',
      merId: '',
      direction: 'rtl',
      activeName: 'detail',
      merCateList: [],
      storeType: [],
      ywy:[],
      nodeKey: 'city_id',
      props: {
        children: 'children',
        label: 'name',
        value: 'id',
        multiple: true,
        lazy: true,
        lazyLoad: this.lazyLoad,
        checkStrictly: true
      },
      ruleValidate: {
        mer_name: [
          { required: true, message: '请输入站点名称', trigger: 'blur' }
        ],
        category_id: [
          { required: true, message: '请选择站点分类', trigger: 'change' }
        ],
        mer_phone: [{ required: true, validator: validatePhone, trigger: 'blur' }],
      },
    };
  },
  filters: {
  },
  mounted() {
    this.getCategorySelect();
    this.getStoreType()
    this.getgetywyuidlist()
    this.getCitys(0)
  },
  methods: {
    getCitys(code = '', level = 1) {

      cityDataLst(code).then(result => {
        this.listLoading = false
        let res = result.data
        switch (level) {
          case 1:
            this.provinceOptions = res
            break;
          case 2:
            this.cityOptions = res
            break;
          case 3:
            this.districtOptions = res
            break;
          case 4:
            this.townOptions = res
            break;
          default:
            break;
        }
      })
    },
    addressSelect(data, index) {
      let addressCode = ''
      //选择任意下拉框需把下一个下拉框清空再获取

      switch (index) {
        case 2:
          this.cityOptions = []
          this.districtOptions = []
          this.townOptions = []
          this.merData.city = ''
          this.merData.county = ''
          this.merData.street = ''
          this.merData.city_id = 0
          this.merData.district_id = 0
          this.merData.district = ''
          addressCode = this.provinceOptions.find(a => a.name == data).id//获取code调接口获取下一级 下方同理
          this.merData.province_id = addressCode
          break;
        case 3:
          this.districtOptions = []
          this.townOptions = []
          this.merData.county = ''
          this.merData.street = ''
          this.merData.district = ''
          this.merData.district_id = 0
          addressCode = this.cityOptions.find(a => a.name == data).id
          this.merData.city_id = addressCode
          break;
        case 4:
          this.townOptions = []
          this.merData.street = ''
          addressCode = this.districtOptions.find(a => a.name == data).id
          this.merData.district_id = addressCode
          break;
        default:
          break;
      }
      if (index == 5) { //此需求是省市区需要中文汉字(name)传给后台，街道需要代码(code)
        this.merData.addressCode = this.townOptions.find(a => a.name == data).id
        this.merData.street_id = this.merData.addressCode
        return
      }
      console.log( this.merData)
      this.getCitys(addressCode, index)
    },
    getgetywyuidlist(){
      getywyuidlist().then(res => {
        this.ywy = res.data
      }).catch(res => {
        this.$message.error(res.message)
      })
    },
    // 站点分类；
    getCategorySelect() {
      merCategoryListApi({
        limit:999
      }).then(res => {
        this.merCateList = res.data.list
      }).catch(res => {
        this.$message.error(res.message)
      })
    },
    /**获取店铺类型 */
    getStoreType(){
      getstoreTypeApi().then(res => {
        this.storeType = res.data
      }).catch(res => {
        this.$message.error(res.message)
      })
    },
    /**修改采集次数 */
    modifyCopy() {
      this.$emit('modifyCopy')
    },
    /**重置表单数据 */
    resetData(){
      this.$refs.merDataField.resetFields();
    },
    /*提交信息*/
    onSubmit(id){
      this.$refs['merDataField'].validate(valid => {
        if (valid) {
          this.loading = true;
          //判定是否选择了省市区
          if(this.merData.province_id <= 0){
            this.$message.error('请选择省份');
            return false
          }
          if(this.merData.city_id <= 0){
            this.$message.error('请选择市');
            return false
          }
          if(this.merData.district_id <= 0){
            this.$message.error('请选择区');
            return false
          }

          merchantUpdate(this.merData)
          .then(async res => {
            this.$message.success(res.message);
            this.loading = false;
            this.$emit('success');
          })
          .catch(res => {
            this.loading = false;
            this.$message.error(res.message);
          });
        }
      });
    },
    /**创建站点 */
    handleCreate(){
      this.$refs['merDataField'].validate((valid) => {
        if (valid) {
          merchantInteCreate(this.merData)
            .then(async (res) => {
              this.$message.success(res.message);
              this.$emit('success');
            })
            .catch((res) => {
              this.$message.error(res.message);
            });
        } else {
          if(!this.merData.mer_name)return this.$message.error('请填写基本信息-站点名称');
        //  if(!this.merData.category_id)return this.$message.error('请选择基本信息-站点分类');
         // if(!this.merData.type_id)return this.$message.error('请选择基本信息-店铺类型');
          if(!this.merData.mer_account)return this.$message.error('请填写账号信息-站点账号');
          if(!this.merData.mer_phone)return this.$message.error('请填写账号信息-联系电话');
        }
      });
    }
  },
};
</script>
<style lang="scss" scoped>
.selWidth{
  width: 100%;
}
.el-tabs--border-card {
  box-shadow: none;
  border-bottom: none;
}
.section {
  padding: 20px 0 5px;
  border-bottom: 1px dashed #eeeeee;
  .title {
    padding-left: 10px;
    border-left: 3px solid #437FFD;
    font-size: 15px;
    line-height: 15px;
    color: #303133;
  }
  .list {
    display: flex;
    flex-wrap: wrap;
    list-style: none;
    padding: 0;
  }
  .item {
    flex: 0 0 calc(100% / 2);
    display: flex;
    margin-top: 16px;
    font-size: 13px;
    color: #606266;

    &:nth-child(2n + 1) {
      padding-right: 20px;
      padding-left: 20px;
    }
    &:nth-child(2n) {
     padding-right: 20px;
    }
  }
  .value {
    flex: 1;
    image {
      display: inline-block;
      width: 40px;
      height: 40px;
      margin: 0 12px 12px 0;
      vertical-align: middle;
    }
  }
}
.info-red{
  color: red;
  font-size: 12px;
}
/deep/.el-input-number.is-controls-right .el-input__inner{
 padding: 0 40px 0 10px;
}
/deep/.el-form-item__label{
  font-weight: normal;
  color: #282828;
}
.tab {
  display: flex;
  align-items: center;
  .el-image {
    width: 36px;
    height: 36px;
    margin-right: 10px;
  }
}
/deep/.el-drawer__body {
  overflow: auto;
}
.gary {
  color: #aaa;
}

</style>
